/*
 * Copyright (C) 2013  Richard Schilling. All rights reserved.
 * contact: coderroadie@gmail.com
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package android.persist.op.sqlite;

import static android.persist.op.sqlite.SQLLogging.SQL_LOG_TAG;

import java.util.Map;
import java.util.Map.Entry;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.persist.config.ClassConfig;
import android.persist.op.Count;
import android.persist.op.OpException;
import android.util.Log;

/**
 * Counts all objects of a given class from the database.
 * 
 * @author Richard Schilling
 * @param <OT> the class of the object to count.
 * @since 1.0
 */
public class SQLiteCount<OT> extends Count<Class<OT>, Long> {

    /**
     * The database that this operation is applied against.
     * 
     * @since 1.0
     */
    private final SQLiteDatabase mDatabase;

    /**
     * Class configuration object for {@link operand}'s type.
     * 
     * @since 1.0
     */
    private final ClassConfig<OT> mConfig;

    /**
     * {@inheritDoc}
     * <p>
     * Creates a new count operation to count objects in the database. If
     * {@code criteria} is null then all objects of the specified class type
     * {@code c} are counted by {@link #call()}.
     * 
     * @param db the database to read from.
     * @param c the class type to count.
     * @param criteria an optional parameter that contains field name/value
     *            pairs to use as selection criteria when counting data in the
     *            data store.
     * @since 1.0
     */
    @SuppressWarnings("unchecked")
    public SQLiteCount(SQLiteDatabase db, Class<OT> c, Map<String, Object> criteria) {
        super(c, criteria);

        if (db == null)
            throw new IllegalArgumentException("db cannot be null");

        if (c == null)
            throw new IllegalArgumentException("o cannot be null");

        this.mDatabase = db;
        this.mConfig = ClassConfig.getConfig(c);

    }

    /**
     * Fetches objects from the data store. Foreign reference fields are set as
     * null. To populate those with data utilize {@link SQLiteReadForeign}.
     * 
     * @since 1.0
     * @throws OpException if the database is closed.
     * @throws PersistExcepton the data cannot be read into a new instance of
     *             the class specified in the constructor.
     */
    @Override
    public Long call() {
        if (!mDatabase.isOpen()) {
            throw new OpException("database is closed");
        }

        StringBuilder query = new StringBuilder();
        query.append("SELECT count(*) FROM '");
        query.append(mConfig.storageName);
        query.append("'");
        if (mCriteria != null) {
            query.append(" WHERE ");
            int i = 0;
            int sz = mCriteria.size();
            for (Entry<String, Object> e : mCriteria.entrySet()) {
                query.append(e.getKey());
                query.append("=");
                query.append(SQLiteUtil.toStringValue(e.getValue()));
                if (i < sz - 1)
                    query.append(" AND");

                i++;

            }

        }

        if (Log.isLoggable(SQL_LOG_TAG, Log.DEBUG)) {
            Log.d(SQL_LOG_TAG, query.toString());
        }

        SQLiteStatement stmt = mDatabase.compileStatement(query.toString());
        return stmt.simpleQueryForLong();

    }

}
